<template>
    <div class='wrapper'>
        <div class="input-box">
            <!-- ($event) -->
            <el-autocomplete clearable @change="changeAdderss" v-model="filterInfo.query.end_address"
                style="width: 100%;" :fetch-suggestions="fetchSuggestions" @select="selectPlace($event)"
                placeholder="请输入地址搜索" popper-class="search-popper" :trigger-on-focus="false">
                <template slot-scope="{ item }">
                    <div style="display:flex;">
                        <div class="name">{{ item.name }}</div>
                        <div
                            style="font-size: 10px;margin-left: 5px; color: #999999;white-space: nowrap; overflow: hidden;  text-overflow: ellipsis; ">
                            {{ item.district }}</div>
                    </div>
                </template>
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
                <!-- <button  style="height: 18px;width: 18px;" src="../../../assets/images/fill.png" /> -->
                <!-- <el-button slot="suffix" type="primary">搜索</el-button> -->
            </el-autocomplete>
            <div v-if="distances" class="radioBox">
                距离：<span>{{ distances }}km</span>

            </div>
            <div class="radioBox">
                柜型：
                <el-radio-group v-model="filterInfo.query.container_size" @change="changeType">
                    <el-radio :label="0">所有</el-radio>
                    <el-radio :label="1">小柜</el-radio>
                    <el-radio :label="2">大柜</el-radio>
                </el-radio-group>
            </div>
            <div class="radioBox">
                类型：
                <el-radio-group v-model="filterInfo.query.success" @change="changeType">
                    <el-radio label="">所有</el-radio>
                    <el-radio :label="0">未成交</el-radio>
                    <el-radio :label="1">成交</el-radio>
                </el-radio-group>
            </div>
            <div class="radioBox">
                单双背：
                <el-radio-group v-model="filterInfo.query.is_dobule_back" @change="changeType">
                    <el-radio :label="2">所有</el-radio>
                    <el-radio :label="0">单背</el-radio>
                    <el-radio :label="1">双背</el-radio>
                </el-radio-group>
            </div>
            <div class="table">
                <el-table v-loading="loading" @row-click="handleRowClick" :data="dataList"
                    :height="dataList.length > 0 ? mapHeight * 0.6 + 'px' : '0px'" :header-cell-style="{
                        background: '#eef1f6',
                        color: '#666',
                        fontSize: '12px'
                    }">
                    <el-table-column type="index" width="50" label="序号" align="center">
                    </el-table-column>
                    <el-table-column prop="amount" label="价格" width="80" align="center">
                    </el-table-column>
                    <el-table-column prop="end_address" width="120" label="地址" align="center">
                    </el-table-column>
                    <el-table-column prop="admin_name" width="100" label="添加人" align="center">
                    </el-table-column>
                    <el-table-column prop="add_time" width="100" label="添加时间" align="center">
                    </el-table-column>
                </el-table>
            </div>
            <!-- <el-button @click="addPriceMap" style="height: 30px;position: absolute;top: 5px;right: -70px;" size="mini"
                type="primary">添加</el-button> -->
            <!-- <div class="table"  v-loading="loading" style="{height: dataList.length > 0 ? tableHeight : '0px';}">
  
        </div> -->
        </div>
        <div :style="{ height: pageParm.tableHeight }" class="mapContainer" id="mapContainer"></div>
    </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import { publishQuotation, getPathDistances } from '../../../api/api'
export default {
    name: "priceMap",
    components: {},
    props: {
        mapHeight: {
            type: Number
        }
    },
    watch: {
        mapHeight () {
            this.pageParm.tableHeight = this.mapHeight + 'px'
            this.initMap()
        }
    },
    data () {
        return {
            // 距离
            distances: "",
            refresh: false,
            loading: false,
            tableHeight: "100%",
            dataList: [],
            map: null,
            geocoder: null,
            address: "",
            container: null,
            markers: [],
            // 过滤相关配置
            filterInfo: {
                query: {
                    page: 1,
                    limit: 50,
                    lng: "",//经度
                    lat: "",//纬度
                    container_size: 0,//集装箱尺寸 1大柜 2小柜
                    is_dobule_back: 2,
                    success: "",
                    start_time: "",
                    end_time: "",
                    end_address: "",
                },
                list: [],
            },
            contentStyleObj: {
                height: "100%",
            },
            // 分页参数
            pageParm: {
                tableHeight: this.mapHeight + 'px', // 表格最大高度
                sort: { order: "descending" },
                total: 0, // 总条数
                loading: true, // 加载动画
                pagesizes: [20, 50, 100, 500], // 分页数量列表
                query: {
                    // 查询条件
                    page: 1, // 当前页
                    limit: 20, // 每页条数
                },
            },
        };
    },
    computed: {},
    methods: {
        addPriceMap () {
            this.$router.push({
                name: 'addpriceMap',
                query: {
                }
            })
        },
        handleRowClick (row, column, event) {
            const rowIndex = this.dataList.indexOf(row);
            this.open(row, rowIndex)
        },
        open (item, index) {
            const that = this;
            if (!that.markers[index]) return
            //  创建自定义信息窗口
            let infoWindowDom = document.createElement("div");
            infoWindowDom.className = "custom-info-window";
            infoWindowDom.innerHTML = `
                <p>工厂地址：${item.end_address}</p>
                <p>抵达次数：${item.count}</p>
                <p>箱型重量：${item.container_type + ' ' + item.weight + '吨'}</p>
                <p>运费价格：${item.amount}</p>
                <p>接单人：${item.real_name}</p>
                <p>联系电话：${item.phone}</p>
                <p>添加时间：${item.date}</p>
              `;
            // 创建信息窗口
            let infoWindow = new AMap.InfoWindow({
                content: infoWindowDom, // 设置信息窗口的内容
                offset: new AMap.Pixel(-12, -40), // 设置信息窗口的偏移量
            });
            infoWindow.open(that.map, that.markers[index].getPosition());
            that.map.setZoomAndCenter(11.6, that.markers[index].getPosition());
        },
        //创建地图标记
        createMarker () {
            const that = this;
            that.dataList.forEach((item, index) => {
                if (!item.end_lng || !item.end_lat) return
                let number = index + 1;
                const marker = new AMap.Marker({
                    position: [item.end_lng, item.end_lat],
                    map: that.map,
                    content: '<div class="custom-marker">' + number + '</div>',
                    offset: new AMap.Pixel(-25, -40),
                });
                //  创建自定义信息窗口
                let infoWindowDom = document.createElement("div");
                infoWindowDom.className = "custom-info-window";
                infoWindowDom.innerHTML = `
                <p>工厂地址：${item.end_address}</p>
                <p>抵达次数：${item.count}</p>
                <p>箱型重量：${item.container_type + ' ' + item.weight + '吨'}</p>
                <p>运费价格：${item.amount}</p>
                <p>接单人：${item.real_name}</p>
                <p>联系电话：${item.phone}</p>
                <p>添加时间：${item.date}</p>
              `;
                // 创建信息窗口
                let infoWindow = new AMap.InfoWindow({
                    content: infoWindowDom, // 设置信息窗口的内容
                    offset: new AMap.Pixel(-12, -40), // 设置信息窗口的偏移量
                });
                // 添加点击事件监听器，显示信息窗口
                marker.on("click", () => {
                    infoWindow.open(that.map, marker.getPosition());
                });
                that.map.add(marker);
                that.markers.push(marker);
            });
            const lat = that.filterInfo.query.lat
            const lng = that.filterInfo.query.lng
            if (lat && lng) {
                //当前位置坐标标记
                let currentIcon = new AMap.Icon({
                    size: new AMap.Size(50, 50), // 图标尺寸
                    image: require("../../../assets/image/currentLocation.png"), // Icon的图像
                    imageOffset: new AMap.Pixel(0, 0), // 图像相对展示区域的偏移量，适于雪碧图等
                    imageSize: new AMap.Size(50, 50), // 根据所设置的大小拉伸或压缩图片
                });
                const currentMarker = new AMap.Marker({
                    position: [lng, lat],
                    map: that.map,
                    icon: currentIcon,
                    offset: new AMap.Pixel(-25, -40),
                });
                that.map.setZoomAndCenter(11.6, [lng, lat]);
                that.map.add(currentMarker);
            } else {
                that.map.setZoomAndCenter(7.5, [117.12654, 36.65840]);
            }
            // console.log('我执行了that.markers>>>>>>', that.markers)
        },
        // 清空地图上的所有标记
        clearMap () {
            if (this.map) {
                this.map.clearMap();
                this.markers = [];
            }
        },
        changeType (e) {
            this.init(this.filterInfo.query)
        },
        changeAdderss (e) {
            if (!e) {
                this.filterInfo.query.container_size = 0;
                this.filterInfo.query.lng = "";
                this.filterInfo.query.lat = "";
                this.init(this.filterInfo.query);
            }
        },
        // selectPlace (selectedItem, name) {
        //     if (selectedItem) {
        //         this.address = selectedItem.district + selectedItem.name;
        //         if (selectedItem.location) {
        //             this.filterInfo.query.lng = selectedItem.location.lng;
        //             this.filterInfo.query.lat = selectedItem.location.lat;
        //             this.init(this.filterInfo.query);
        //         } else {
        //             this.address = "";
        //             this.filterInfo.query.container_size = 0;
        //             this.filterInfo.query.lng = "";
        //             this.filterInfo.query.lat = "";
        //             this.$message.error("请输入具体位置定位！");
        //         }
        //     }
        // },
        selectPlace (selectedItem) {
            if (selectedItem && selectedItem.location) {
                this.filterInfo.query.lng = selectedItem.location.lng;
                this.filterInfo.query.lat = selectedItem.location.lat;
                this.filterInfo.query.end_address = selectedItem.name; // 更新地址显示
                this.init(this.filterInfo.query); // 触发数据加载和地图定位
            }
        },
        //搜索
        // fetchSuggestions (queryString, callback) {
        //     const autoComplete = new AMap.Autocomplete({
        //         city: "全国",
        //     });

        //     autoComplete.search(queryString, (status, result) => {
        //         if (status === "complete") {
        //             console.log('result>>>>>>', result)
        //             callback(result.tips);
        //         }
        //     });
        // },
        fetchSuggestions (queryString, callback) {
            const autoComplete = new AMap.Autocomplete({ city: "全国" });
            autoComplete.search(queryString, (status, result) => {
                if (status === "complete") {
                    // 过滤掉没有location的项
                    const validItems = result.tips.filter(item => item.location);
                    callback(validItems);
                }
            });
        },
        // // 加载地图
        // loadMap () {
        //     this.initMap()
        // },
        //地图初始化
        initMap () {
            const that = this;
            AMapLoader.reset();
            AMapLoader.load({
                key: localStorage.getItem('map_key'), // 申请好的Web端开发者Key，首次调用 load 时必填 "1ec835bc9134155436573b152f3a2d8c"
                version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: ["AMap.AutoComplete", 'AMap.Geocoder'],
            })
                .then((AMap) => {
                    this.map = new AMap.Map("mapContainer", {
                        // 设置地图容器id
                        viewMode: "3D", // 是否为3D地图模式
                        zoom: 7.5, // 初始化地图级别
                        center: [117.12654, 36.65840], // 初始化地图中心点位置
                    });
                    this.geocoder = new AMap.Geocoder();
                    // 添加点击事件监听器
                    this.map.on('click', (event) => {
                        console.log('event>>>>>>', event)
                        // 获取点击位置的经纬度
                        const lnglat = event.lnglat;
                        this.geocoder.getAddress(
                            lnglat,
                            (status, result) => {
                                if (status === "complete" && result.info === "OK") {
                                    this.$set(this.filterInfo.query, "end_address", result.regeocode.formattedAddress);
                                }
                            }
                        );
                        if (!this.filterInfo.query.end_address) {
                            const formData = new FormData()
                            formData.append('lat', event.lnglat.lat)
                            formData.append('lng', event.lnglat.lng)
                            formData.append('end_address', this.filterInfo.query.end_address)
                            formData.append('type', '0')
                            // 获取距离
                            getPathDistances(formData).then((res) => {
                                console.log('res>>>>>>', res)
                                this.distances = res.data.path_distance

                            }).catch((err) => {

                                console.log(err)
                            })

                        }
                        this.filterInfo.query.lng = event.lnglat.lng;
                        this.filterInfo.query.lat = event.lnglat.lat;
                        this.init(this.filterInfo.query);
                    })
                    this.init(this.filterInfo.query);
                })
                .catch((e) => {
                    console.log(e);
                });
        },
        init (data) {
            this.loading = true
            this.clearMap()
            const formData = new FormData()
            for (const key in data) {
                formData.append(key, data[key])
            }

            if (data.end_address) {
                formData.append('type', '0')
                // 获取距离
                getPathDistances(formData).then((res) => {
                    console.log('res>>>>>>', res)
                    this.distances = res.data.path_distance

                }).catch((err) => {

                    console.log(err)
                })

            }
            publishQuotation(formData).then((res) => {
                console.log('res>>>>>>', res)
                this.dataList = res.data.data
                if (this.map) {
                    this.createMarker();
                }
                this.loading = false
            }).catch((err) => {
                this.loading = false
                console.log(err)
            })
        },
        getHeight () {
            if (this.contentStyleObj.height == "100%") {
                // var height =
                //   window.innerHeight - parseInt(this.contentStyleObj.height) - 0;
                var height = window.innerHeight - 60;
            } else {
                var height =
                    window.innerHeight - parseInt(this.contentStyleObj.height) - 156;
            }
            this.pageParm.tableHeight = height + "px";
            this.tableHeight = (height - 130) + "px";
        },
        //enter 事件防止全局触发
        upenter () {
            const that = this;
            document.onkeydown = (e) => {
                //13表示回车键，baseURI是当前页面的地址，为了更严谨，也可以加别的，可以打印e看一下
                if (e.keyCode === 13 && e.target.baseURI.match("priceMap")) {
                    //回车后执行搜索方法
                    that.filterInfo.query.page = 1;
                    that.init(that.filterInfo.query);
                }
            };
        },
    },
    beforeCreate () { }, //生命周期 - 创建之前
    created () {
        if (this.$route.name == "priceMap") {
            // this.init(this.filterInfo.query);
            this.getHeight()
            this.upenter();
        }
    },
    beforeMount () { }, //生命周期 - 挂载之前
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted () {
        // 配置高德地图安全码
        window._AMapSecurityConfig = {
            securityJsCode: localStorage.getItem('map_secret'), // 申请key对应的秘钥"b8bcc8499e8eca3d7d9d0d9d60c4b385"
        };

    },
    beforeUpdate () { }, //生命周期 - 更新之前
    updated () {
    }, //生命周期 - 更新之后
    beforeDestroy () { }, //生命周期 - 销毁之前
    destroyed () { }, //生命周期 - 销毁完成
    activated () {
        if (this.$route.name == "priceMap" && this.refresh) {
            // console.log('activated>>>>>>>>>')
            this.initMap()
            this.getHeight()
            this.upenter();
            this.refresh = false;
        }
    }, //如果页面有keep-alive缓存功能，这个函数会触发
    deactivated () {
        // console.log('deactivated>>>>>>>>>')
        this.refresh = true;
    },
}
</script>
<style scoped lang='scss'>
.wrapper {
    position: relative;
}

.table {
    width: 100%;
    box-sizing: border-box;
    transition: height .7s ease;

    ::v-deep .el-table {
        transition: height .7s ease;
    }

    ::v-deep .el-table .el-table__cell {
        padding: 8px 0;
    }

    ::v-deep .cell {
        font-size: 12px;
    }

    ::v-deep .el-table__body-wrapper::-webkit-scrollbar {
        // width: 20px;
    }
}

.mapContainer {
    width: 100%;
    box-sizing: border-box;
}

::v-deep .custom-marker {
    position: relative;
    width: 24px;
    height: 40px;
    text-align: center;
    // line-height: 63px;
    color: white;
    background-image: url('https://webapi.amap.com/theme/v1.3/markers/b/mark_bs.png');
    background-size: contain;
}


.input-box {
    margin: 20px;
    width: 350px;
    background-color: #fff;
    position: absolute;
    z-index: 1;

    ::v-deep .el-input__prefix {
        display: flex;
        align-items: center;
        left: 0px;
    }

    ::v-deep .el-input__inner {
        border: none;
        // height: 100%;
        // border-bottom: 1px solid #d9d9d9;
        border-radius: 0;
        font-size: 14px;
    }
}

.radioBox {
    font-size: 14px;
    padding: 10px;
    border-top: 1px solid #d9d9d9;
}


::v-deep .custom-info-window {
    width: 300px;
    font-size: 12px;
}
</style>